import { SaveType } from './../BackupManager';
import { formatTime, getUid, uint8ArrayToString } from 'src/util/common';
import { LocalFile, LocalFileService, TableData } from './LocalFileService';
import { portal as saveLoading } from 'src/components/Project/modals/SaveLoading.vue';
import { portal as OpenLoading } from 'src/components/Project/modals/OpenLoading.vue';
import xlsx from 'xlsx';
import { MofModelRepositoryHelper, SysMLUtilHelper } from 'src/api/sysml-imports';
import { storage } from "src/util/common";
import { svgAsDataUri, saveSvgAsPng } from 'save-svg-as-png';
import jsPDF from 'jspdf';
import { VERSION } from '@/constants/constants';
import { graphHelper } from '@/api/GraphHelper';
export class LocalFileElectron implements LocalFile {
  dialog:any
  appPath: string
  constructor(){
    this.dialog = window.$ele.electron.remote.dialog;
    this.appPath = window.$ele.electron.remote.app.getAppPath();
  }
  getInitProject(){
    return LocalFileService.getInitProject();
  }
  saveProject(project:Project):Promise<any> {
    return saveLoading.popup({
      time: 2,
      saveFn: async () => {
        await this.saveProjectSilence(project);
        project.backupManager.addBackup(SaveType.MANUAL);
      }
    });
  }
  saveProjectXML(project:Project):Promise<any> {
    return saveLoading.popup({
      time: 2,
      saveFn: async () => {
        await this.saveProjectSilenceXML(project);
      }
    });
  }

  getBrowserWindow(){
    return window.$ele.electron.remote.BrowserWindow.getFocusedWindow();
  }
  showSaveDialog(option?:any){
    return this.dialog.showSaveDialogSync(
      this.getBrowserWindow(),
      option || {
        title: '另存为',
        filters: [{ name: 'M-Design Project', extensions: ['md3'] }, { name: '只读M-Design Project', extensions: ['md3r'] }]
      });

  }
  showSaveDialogXML(option?:any){
    return this.dialog.showSaveDialogSync(
      this.getBrowserWindow(),
      option || {
        title: '导出',
        filters: [{ name: 'M-Design Project', extensions: ['xml'] }, { name: '只读M-Design Project', extensions: ['xmlr'] }]
      });

  }
  /**
   * 弹出打开文件弹窗
   */
  showOpenDialog(option?:any){
    const filePaths = this.dialog.showOpenDialogSync(
      this.getBrowserWindow(),
      option || { properties: ['openFile'],  title: '打开', buttonLabel: "打开", filters: [{ name: 'M-Design Project', extensions: [ 'md3', 'md3t' ] }] }
    );
    return filePaths && filePaths[0];
  }
  /**
   * 弹出打开xml文件弹窗
   */
  showOpenDialogXML(option?:any){
    const filePaths = this.dialog.showOpenDialogSync(
      this.getBrowserWindow(),
      option || { properties: ['openFile'],  title: '导入', buttonLabel: "打开", filters: [{ name: 'M-Design Project', extensions: [ 'xml' ] }] }
    );
    return filePaths && filePaths[0];
  }

  async saveAsProject(project:Project, repalceCurrent = true):Promise<any> {
    const filePath = this.showSaveDialog({ title: '另存为' });
    if (!filePath) return;
    const path = window.$ele.path;
    const projectName = path.basename(filePath,  '.md3');
    const projectPath = path.dirname(filePath);
    const projectCopy = { ...project };
    projectCopy.config = { ...projectCopy.config };
    projectCopy.config.projectPath = projectPath;
    projectCopy.config.projectFullPath = filePath;
    projectCopy.config.projectName = projectName;
    await this.saveProject(projectCopy);
    if (repalceCurrent) {
      project.config.projectPath = projectPath;
      project.config.projectFullPath = filePath;

      project.config.projectName = projectName;
    }
    //// 如果保存成功，把当前的项目的名称和路径改为新的路径和名称，相当于打开了另存为的项目

  }
  async saveAsProjectMD3(project:Project, repalceCurrent = true):Promise<any> {
    const filePath = this.showSaveDialog({ title: '导出' });
    if (!filePath) return;
    const path = window.$ele.path;
    const projectName = path.basename(filePath,  '.md3');
    const projectPath = path.dirname(filePath);
    const projectCopy = { ...project };
    projectCopy.config = { ...projectCopy.config };
    projectCopy.config.projectPath = projectPath;
    projectCopy.config.projectFullPath = filePath;
    projectCopy.config.projectName = projectName;
    await this.saveProject(projectCopy);
    if (repalceCurrent) {
      project.config.projectPath = projectPath;
      project.config.projectFullPath = filePath;

      project.config.projectName = projectName;
    }
    //// 如果保存成功，把当前的项目的名称和路径改为新的路径和名称，相当于打开了另存为的项目

  }

  async saveAsProjectXML(project:Project, repalceCurrent = true):Promise<any> {
    const filePath = this.showSaveDialogXML();
    if (!filePath) return;
    const path = window.$ele.path;
    const projectName = path.basename(filePath,  '.xml');
    const projectPath = path.dirname(filePath);
    const projectCopy = { ...project };
    projectCopy.config = { ...projectCopy.config };
    projectCopy.config.projectPath = projectPath;
    projectCopy.config.projectFullPath = filePath;
    projectCopy.config.projectName = projectName;
    await this.saveProjectXML(projectCopy);
    if (repalceCurrent) {

      //// 如果保存成功，把当前的项目的名称和路径改为新的路径和名称，相当于打开了另存为的项目
      project.config.projectPath = projectPath;
      project.config.projectFullPath = filePath;

      project.config.projectName = projectName;
    }
  }

  /**
   * 弹出文件选择框，读取项目
   */
  async openProject(filePath?:string):Promise<any> {
    if (!filePath) {
      filePath = this.showOpenDialog({ title: '打开' });
    }
    if (!filePath){
      return Promise.reject({ cancel: true });
    }

    return await this.readProject(filePath);
  }

  /**
   * 读取项目
   * @param filePath
   */
  async readProject(filePath:string):Promise<any> {
    const blob = await LocalFileService.readFile(filePath, 'utf-8');
    //// const data = new Uint8Array(projectBlob);
    //// projectJsonString = uint8ArrayToString(data);
    //// JSON.parse(blob);
    const projectData = JSON.parse(blob as string);
    const existProject = app.proxy.projects.get(projectData.config.id);
    if (existProject){

      let cancel = false;
      await app.$Confirm.popup({ //// 如果路径不同则表示是 相同id的不同文件，需要先关闭再打开，
        title: '提示',
        content: '项目ID已存在',
        subContent: '必须关闭已存在的项目，才能继续打开，是否继续',
        showCheckbox: false,
        status: 'info',
        cancelText: '取消',
        okText: '继续',

      }).then(res => {
        LocalFileService.removeProject(existProject);

      }).catch(e => {
        e && console.error(e);
        cancel = true;
      });
      if (cancel){
        return Promise.reject({ cancel: true });

      }

    }

    let project:Project = null;
    await OpenLoading.popup({
      time: 1,
      msg: '读取中...',
      Fn: async () => {
        project = await LocalFileService.loadProjectData(blob);
        console.log('project', project);
        const path = window.$ele.path;
        project.config.projectName = project.config.online ? path.basename(filePath,  '.md3t') : path.basename(filePath,  '.md3');
        project.config.projectPath = path.dirname(filePath);
        project.config.projectFullPath = filePath;
      }
    });
    return Promise.resolve(project);

  }

  /**
   * 读取项目
   * @param filePath
   */
  async importProject(filePath:string):Promise<any> {
    if (!filePath) {
      filePath = this.showOpenDialog({ title: '导入' });
    }
    if (!filePath){
      return Promise.reject({ cancel: true });
    }
    const blob = await LocalFileService.readFile(filePath);
    let project:Project = null;
    console.log('blob.toString()', blob.toString());

    await OpenLoading.popup({
      time: 1,
      msg: '读取中...',
      Fn: async () => {
        project = await LocalFileService.parseProjectData(blob);
        console.log('project', project);
        const path = window.$ele.path;
        project.config.projectName = path.basename(filePath,  '.md3');
        project.config.projectPath = path.dirname(filePath);
        project.config.projectFullPath = filePath;
      }
    });
    return Promise.resolve(project);

  }
  /**
   * 读取xml项目
   * @param filePath
   */
  async importProjectXML(filePath:string):Promise<any> {
    if (!filePath) {
      filePath = this.showOpenDialogXML();
    }
    if (!filePath){
      return Promise.reject({ cancel: true });
    }
    const blob = await LocalFileService.readFile(filePath);
    console.log('blob-----------', blob);

    const parser = require('fast-xml-parser');
    const options = {
      ignoreAttributes: false,
      allowBooleanAttributes: true,
      parseNodeValue: true,
      parseAttributeValue: true
    };
    const str = blob.toString();
    console.log('导入后的str', str);

    let result = parser.parse(str, options);
    result = result.xml;
    console.log(result.model);
    result.model = result.model.replace(/_&lt;_/g, '<').replace(/_&gt;_/g, '>');
    const nodeStatus = {};
    Object.keys(result.onlineConfig.nodeStatus).forEach(key => {
      const key2 = key.substring(1);
      nodeStatus[key2] = result.onlineConfig.nodeStatus[key];
    });
    result.onlineConfig.nodeStatus = nodeStatus;
    console.log('导入后的result', result);
    const model = result.model.text;
    console.log('model------------------------------------------------------------', model);

    if (typeof result.config.rootIds === 'string'){
      const arr = [];
      arr.push(result.config.rootIds);
      result.config.rootIds = arr;
    }
    if (result.config && result.config.projectName) result.config.projectName = result.config.projectName.toString();
    if (result.config && result.config.version) result.config.version = result.config.version.toString();
    if (result.onlineConfig && result.onlineConfig.version) result.onlineConfig.version = result.onlineConfig.version.toString();
    if (result.onlineConfig && result.onlineConfig.privileges) result.onlineConfig.privileges = {};

    let project:Project = null;
    console.log('解析后的结果', JSON.stringify(result));

    await OpenLoading.popup({
      time: 1,
      msg: '读取中...',
      Fn: async () => {
        project = await LocalFileService.parseProjectData(JSON.stringify(result));
        console.log('project', project);
        const path = window.$ele.path;
        project.config.projectName = path.basename(filePath,  '.xml');
        project.config.projectPath = path.dirname(filePath);
        project.config.projectFullPath = filePath;
      }
    });
    return Promise.resolve(project);
  }

  //// reloadProject():Promise<any> {
  ////   return LocalFileService.reloadProject();
  //// }

  switchToProject(project:Project){
    return LocalFileService.switchToProject(project);
  }

  async openProfile():Promise<any> {
    let appPath = window.process.cwd();
    const env = process.env.NODE_ENV;
    const path = window.$ele.path;
    let profilePath = env === 'development' ? path.resolve(appPath, './public/statics/profile') : path.resolve(appPath, './resources/dist/statics/profile');
    console.log('profilePath', profilePath);
    if (!window.$ele.fs.existsSync(profilePath)) {
      profilePath = appPath;
    }
    const filePathes = this.showOpenProfileDialog(
      {
        defaultPath: profilePath,
        properties: ['openFile'],
        buttonLabel: "导入",
        filters: [{ name: 'M-Design Profile', extensions: ['md3p'] }]
      }
    );
    if (!filePathes) return Promise.reject();
    console.log("导入的路径:", filePathes);
    return this.importProfile(app.activeProject, filePathes);

    //// 具体需求出来后更改为
    //// 1.校验
    //// 2.填充依赖
    //// 3.重新加载项目
  }

  showOpenProfileDialog(option?:any){
    return this.dialog.showOpenDialogSync(
      this.getBrowserWindow(),
      option || {
        properties: ['openFile'],
        buttonLabel: "导入",
        filters: [{ name: 'M-Design Profile', extensions: ['md3p'] }]
      }
    );
  }

  async importProfile(project:Project, filePaths:string[]):Promise<any>{
    let projectDepencies = project.config.dependencies;
    const map = new Map();
    projectDepencies.forEach(dependency => {
      map.set(dependency.dependencyId, true);
    });
    const currentDepenies = [];
    for (let i = 0; i < filePaths.length; i++){
      let filePath = filePaths[i];
      await LocalFileService.loadProfile(filePath, map);
    }
    SysMLUtilHelper.importModule(project.config.id, [...map.values()].filter(i => i !== true), currentDepenies);
  }

  exportProfile(graphNode: GraphNode):Promise<any> {
    const fileDefaultName = graphNode.title;
    let appPath = window.process.cwd();
    const path = window.$ele.path;
    const env = process.env.NODE_ENV;
    let profilePath = env === 'development' ? path.resolve(appPath, './public/statics/profile') : path.resolve(appPath, './resources/dist/statics/profile');
    if (!window.$ele.fs.existsSync(profilePath)) {
      profilePath = appPath;
    }
    return new Promise((rs, rj) => {
      const filePath = this.showSaveDialog({
        title: 'profile',
        defaultPath: path.resolve(profilePath, `./${fileDefaultName}`),
        filters: [{ name: 'M-Design Profile', extensions: [ 'md3p' ] }]
      });
      if (!filePath) return rj();

      const projectName = path.basename(filePath, '.md3p');
      const projectPath = '/statics/profile/';
      const projectFullPath = '/statics/profile/' + projectName + '.md3p';
      const profileDataStr = LocalFileService.parseToProfileData(app.activeProjectId, app.selectedElement.model, projectPath, projectFullPath, projectName);
      LocalFileService.writeFile(filePath, profileDataStr).then(() => {
        app.$messageBox.success({ id: 120 });
        rs(true);
      });
    });

  }

  exportPackage(graphNode: GraphNode){
    const fileDefaultName = graphNode.title;
    let appPath = window.process.cwd();
    const path = window.$ele.path;
    const projectId = app.activeProject.config.id;
    console.log("当前保存路径:", path.resolve(appPath, `./projects/${fileDefaultName}`));
    return new Promise((rs, rj) => {
      const filePath = this.showSaveDialog({
        defaultPath: path.resolve(appPath, `./projects/${fileDefaultName}`),
        filters: [{ name: 'M-Design Project', extensions: [ 'md3'] }]
      });
      if (!filePath) return rj();
      const exportId = getUid();
      const config = {
        rootIds: [app.selectedElement.model.id],
        id: exportId,
        projectName: path.basename(filePath, '.md3'),
        projectPath: path.dirname(filePath),
        projectFullPath: filePath,
        projectDescription: '',
        createdDate: formatTime(Date.now()),
        updateDate: formatTime(Date.now()),
        version: VERSION,
        dependencies: app.activeProject.config.dependencies,
        online: false
      };
      let selectModels = new Array(graphNode.model);
      let modelStr = SysMLUtilHelper.exportPackage(projectId, SysMLUtilHelper.toArrayList(selectModels));
      let project = {
        config: config,
        model: modelStr
      };
      LocalFileService.writeFile(filePath, JSON.stringify(project)).then(() => {
        app.$messageBox.success({ id: 120 });
        rs(true);
      });
    });
  }

  async beforeOpenExcelAndReqif(type) {
    const typeConfig = {
      fileName: '',
      typeName: '',
      fileType: ''
    };
    switch (type) {
      case 'excel':
        typeConfig.fileName = '需求表导入模版.xlsx';
        typeConfig.typeName = 'Excel';
        typeConfig.fileType = 'xlsx';
        break;
      case 'reqif':
        typeConfig.fileName = '需求表导入模版.reqif';
        typeConfig.typeName = 'Reqif';
        typeConfig.fileType = 'reqif';
        break;
      default:
        break;
    }
    let result = {
      checked: false
    };
    if (!storage.get(`notTip-importTable-${type}`)) {
      result = await app.$Confirm
        .popup({
          title: "提示",
          subTitle: `导入${typeConfig.typeName}`,
          content: `系统只读取${typeConfig.typeName}的id, name, text字段。`,
          subContent: "导入后将生成新的需求表和需求放在独立的包内。",
          showCheckbox: true,
          checkboxText: "不再提示",
          status: "warn",
          cancelText: '',
          centerBtnText: '下载模板',
          onClickCenter: () => {
            const path = window.$ele.path;
            const env = process.env.NODE_ENV;
            console.log('env', env);
            let appPath = window.process.cwd();
            //// const process = window.require('process');
            //// let appPath = process.cwd();
            console.log('appPath', window.process.cwd(), process.cwd(), window.$ele.electron.remote.app.getAppPath(), process.env.PORTABLE_EXECUTABLE_DIR);
            let defaultFilePath = env === 'development' ? path.resolve(appPath, './public/statics') : path.resolve(appPath, './resources/dist/statics');
            let defaultPath = path.resolve(defaultFilePath, "./exports");
            if (window.$ele.fs.existsSync(defaultPath)) {
              defaultFilePath = path.resolve(defaultPath, `./${typeConfig.fileName}`);
            } else {
              defaultFilePath = path.resolve(defaultFilePath, `./${typeConfig.fileName}`);
            }

            const filePath = this.showSaveDialog({
              title: "下载模板",
              defaultPath: defaultFilePath,
              filters: [
                { name: "M-Design", extensions: [typeConfig.fileType] }
              ],
            });
            if (!filePath) return false;

            const sourceFilePath = env === 'development' ? path.resolve(
              appPath,
              `./public/statics/files/${typeConfig.fileName}`
            ) : path.resolve(appPath, `./resources/dist/statics/files/${typeConfig.fileName}`);
            //// console.log(sourceFilePath, filePath);
            window.$ele.fs.copyFile(sourceFilePath, filePath,  (err) => {
              if (err) {
                app.$messageBox.error({ text: `下载失败` });
              } else {
                app.$messageBox.success({ text: '下载成功' });
              }
            });
          }
        })
        .catch(e => {
          e && console.error(e);
          return false;
        });
      if (result.checked) {
        storage.set(`notTip-importTable-${type}`, true);
      }
    }
    return result;
  }

  async openExcel(type) {
    const result = await this.beforeOpenExcelAndReqif(type);
    console.log('result', result);
    if (!result) return Promise.reject();
    const path = window.$ele.path;
    const filePath = this.showOpenProfileDialog(
      {
        properties: ['openFile'],
        buttonLabel: "导入Excel",
        filters: [{ name: 'M-Design Profile', extensions: ['xlsx'] }]
      }
    );
    if (!filePath) return Promise.reject();
    const file = await LocalFileService.readFile(filePath[0]);
    const data = {
      data: file,
      name: ''
    };
    data.name = path.basename(filePath[0], '.xlsx');
    //// console.log('file', result.name, filePath, path.basename(filePath[0], '.xlsx'));
    return new Promise((rs, rj) => {
      if (data) {
        rs(data);
      } else {
        rj();
      }
    });
  }

  async openReqif(type){
    const result = await this.beforeOpenExcelAndReqif(type);
    console.log('result', result);
    if (!result) return Promise.reject();
    const filePaths = this.dialog.showOpenDialogSync(
      this.getBrowserWindow(),
      { properties: ['openFile'], filters: [{ name: 'M-Design',  extensions: [ 'reqif' ] }] }
    );
    const filePath = filePaths && filePaths[0];
    if (!filePath) return;
    const data = await LocalFileService.readFile(filePath);
    const path = window.$ele.path;
    const name = path.basename(filePath, '.reqif');

    //// console.log('name', name, );
    return { data, name };
  }

  exportRequirementTableExcel(tableData: TableData, name: string, format: any):Promise<any> {
    //// TODO
    return new Promise((rs, rj) => {
      const jsonData = [];
      this.travelRow(tableData.visibleRows, (row) => {
        const result = {};
        row.cells.forEach(cell => {
          const value = cell.value;
          let name = cell.name;
          if (format && format[name] !== undefined) {
            name = format[name];
          }
          if (Array.isArray(value)){
            result[name] = value.map(val => val.name).join('\r\n');
          } else if (value instanceof Object) {
            result[name] = value.name;
          } else {
            result[name] = value;
          }
        });
        jsonData.push(result);
      });
      let ss = xlsx.utils.json_to_sheet(jsonData); //// 通过工具将json转表对象
      let keys = Object.keys(ss).sort(); //// 排序 [需要注意，必须从A1开始]

      let ref = keys[1] + ':' + keys[keys.length - 1]; //// 这个是定义一个字符串 也就是表的范围[A1:C5]

      let workbook = { //// 定义操作文档
        SheetNames: ['Sheet1'], //// 定义表明
        Sheets: {
          'Sheet1': Object.assign({}, ss) //// 表对象[注意表明]
        },
      };
      xlsx.writeFile(workbook, name + '.xlsx'); //// 将数据写入文件
    });
  }
  exportRequirementTableReqif(tableData: TableData, name: string):Promise<any> {
    //// TODO
    return new Promise((rs, rj) => {

    });

  }
  /**
   * 直接保存文件
   * @param project
   */
  async saveProjectSilence(project:Project):Promise<any>{
    project.config.updateDate = formatTime(Date.now());
    let configStr = JSON.stringify(project.config);
    console.log("加载配置:", configStr);
    console.log("加载模型:", project.metadata.sysml.model.model);
    const blob = LocalFileService.parseProjectToBlob(project);
    await LocalFileService.writeFile(window.$ele.path.resolve(project.config.projectPath, project.config.projectName + (project.config.online ? '.md3t' : '.md3') ), blob);
    project.ui.modified = false;
    LocalFileService.updateRecentProjects(project);
    return;

  }
  async saveProjectSilenceXML(project:Project):Promise<any>{
    project.config.updateDate = formatTime(Date.now());
    let configStr = JSON.stringify(project.config);
    console.log("加载配置:", configStr);
    console.log("加载模型:", project.metadata.sysml.model.model);
    const blob = LocalFileService.parseProjectToBlob(project);

    const options = {
      arrayMode: true,
      //// attributeNamePrefix: "",
      ignoreAttributes: false,
      allowBooleanAttributes: true,
      parseNodeValue: true,
      parseAttributeValue: true
    };

    const Parser = require("fast-xml-parser").j2xParser;
    const blobObj = JSON.parse(blob);
    console.log('projectData ', blobObj);
    blobObj.model = blobObj.model.replace(/</g, '_&lt;_').replace(/>/g, '_&gt;_');
    const nodeStatus = {};
    Object.keys( blobObj.onlineConfig.nodeStatus).forEach(key => {
      nodeStatus['k' + key] =  blobObj.onlineConfig.nodeStatus[key];
    });
    blobObj.onlineConfig.nodeStatus = nodeStatus;

    //// delete blobObj.model;
    const parser = new Parser(options);
    const result = parser.parse({ xml: blobObj });
    console.log('result', result);
    //// const domParser = new DOMParser();
    //// let doc = domParser.parseFromString(JSON.stringify(blobObj), 'text/xml');
    //// console.log('doc------------', doc);
    const timestamp = new Date().getTime();

    await LocalFileService.writeFile(window.$ele.path.resolve(project.config.projectPath, project.config.projectName + timestamp + (project.config.online ? '.xml' : '.xml') ), result);
    project.ui.modified = false;
    project.config.projectFullPath = window.$ele.path.resolve(project.config.projectPath, project.config.projectName + timestamp + (project.config.online ? '.xml' : '.xml') );

    LocalFileService.updateRecentProjects(project);
    return;

  }
  /**
   * 重新加载项目，删除并重新加载
   * @param project
   * @returns
   */
  async reloadProject(project: Project, autoSave = true): Promise<Project> {
    //// const projectId = project.config.id;
    //// project.config.updateDate = formatTime(Date.now());
    //// console.log("加载模型:", project.metadata.sysml.model.model);
    //// const blob = LocalFileService.parseProjectToBlob(project);
    if (autoSave){
      await this.saveProjectSilence(project);

    }
    LocalFileService.removeProject(project);

    //// app.proxy.projects.delete(projectId);
    //// //// SysMLUtilHelper.removePoolById(projectId);
    //// MofModelRepositoryHelper.removePool(projectId);

    let newProject = await this.openProject(project.config.projectFullPath); //// .loadProjectData(blob);
    return newProject;
  }

  travelRow(rows: Array<UmlShape>, fn: (row: UmlShape) => void){
    rows.forEach(row => {
      fn(row);
      if (row.children){
        this.travelRow(row.children, fn);
      }
    });

  }
  //// 下载
  downLoadFile({ filename, content, contentType, selectPath }){
    const path = require('path');
    if (content instanceof ArrayBuffer){
      content = Buffer.from(content);
    }
    const str = uint8ArrayToString(content);
    const projectData = JSON.parse(str);
    console.log(projectData);
    const modelStr = projectData.model;

    projectData.model = JSON.parse(projectData.model);
    projectData.onlineConfig.nodeStatus = {};
    projectData.model.forEach(model => {
      projectData.onlineConfig.nodeStatus[model.id] = 4;

    });
    projectData.model  = modelStr;
    content = JSON.stringify(projectData);
    window.$ele.fs.writeFileSync( selectPath, content);
  };

  exportImage(path, graphContent, type, overwrite) {
    if (window.$ele.fs.existsSync(path)) { //// 判断文件是否存在
      if (!overwrite) {
        return Promise.reject({ text: '文件已存在' });
      }
    }
    return svgAsDataUri(graphContent.querySelector('.geDiagramContainer > svg')).then(uri => {
      return new Promise((res, rej) => {
        const image = new Image();
        image.src = uri;
        image.onload = () => {
          const canvas = document.createElement('canvas');
          document.body.appendChild(canvas);
          const ctx = canvas.getContext('2d');
          //// console.log(image.width, image.height);
          let dateBuffer = null;
          if (type === 'jpg') {
            //// 提高清晰度
            [canvas.width, canvas.height] = [image.width * 2, image.height * 2];
            [canvas.style.width, canvas.style.height] = [image.width + 'px', image.height + 'px'];
            ctx.scale(2, 2);
            ctx.drawImage(image, 0, 0);
            const url = canvas.toDataURL('image/jpeg');
            let base64 = url.replace(/^data:image\/.+;base64,/, "");
            dateBuffer = Buffer.from(base64, 'base64');
          } else if (type === 'pdf') {
            let imgWidth = 595.28;
            let imgHeight = 592.28 / image.width * image.height;

            //// 提高清晰度
            [canvas.width, canvas.height] = [image.width * 3, image.height * 3];
            [canvas.style.width, canvas.style.height] = [image.width + 'px', image.height + 'px'];
            ctx.scale(3, 3);

            ctx.drawImage(image, 0, 0, imgWidth, imgHeight);
            const url = canvas.toDataURL('image/png');
            const pdf = new jsPDF();
            pdf.addImage(url, 'PNG', 0, 0, imgWidth, imgHeight);
            const arrayBuffer = pdf.output('arraybuffer');
            dateBuffer = Buffer.from(arrayBuffer);
          }
          this.writeImageFile(path, dateBuffer, res, rej);
          document.body.removeChild(canvas);
        };
      });
    });
  };

  writeImageFile(path, data, res, rej) {
    //// console.log('dateBuffer', data);
    const dirname = window.$ele.path.dirname(path);
    if (!window.$ele.fs.existsSync(dirname)) { //// 文件夹不存在则创建
      window.$ele.fs.mkdirSync(dirname);
    }
    window.$ele.fs.writeFile(path, data, err => {
      if (err) {
        rej(err);
      } else {
        res(true);
      }
    });
  };

  openFile(filePath) {
    const path = window.$ele.path;
    const env = process.env.NODE_ENV;
    let appPath = window.process.cwd();
    //// const process = window.require('process');
    //// let appPath = process.cwd();
    console.log('appPath', appPath);
    let defaultFilePath = env === 'development' ? path.resolve(appPath, './public/statics' + filePath) : path.resolve(appPath, './resources/dist/statics' + filePath);
    const { shell } = window.require('electron');
    shell.openItem(defaultFilePath);
  }

}
